package com.digitalchina.lxnsy.activity.old;

import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.apkfuns.logutils.LogUtils;
import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.adapter.OrdersDetailsAdapter;
import com.digitalchina.lxnsy.api.BusinessDataMall;
import com.digitalchina.lxnsy.api.BusinessOrders;
import com.digitalchina.lxnsy.base.BaseActivity;
import com.digitalchina.lxnsy.constant.MSG;
import com.digitalchina.lxnsy.constant.URL;
import com.digitalchina.lxnsy.entity.CancelReasonVO;
import com.digitalchina.lxnsy.entity.CartVO;
import com.digitalchina.lxnsy.entity.DataMallVO;
import com.digitalchina.lxnsy.entity.OrderListVO;
import com.digitalchina.lxnsy.interfaces.IPreviewCallBack;
import com.digitalchina.lxnsy.toolkit.CustomDialog;
import com.digitalchina.lxnsy.toolkit.DateStyle;
import com.digitalchina.lxnsy.toolkit.DateUtil;
import com.digitalchina.lxnsy.toolkit.FastJsonUtil;
import com.digitalchina.lxnsy.toolkit.GotoUtil;
import com.digitalchina.lxnsy.toolkit.MIMETypeUtil;
import com.digitalchina.lxnsy.toolkit.MathExtend;
import com.digitalchina.lxnsy.toolkit.StringUtil;
import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadLargeFileListener;
import com.liulishuo.filedownloader.FileDownloader;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;

/**
 * ================================================
 * 项目名称：BigData
 * 类描述：
 * 包名：com.digitalchina.bigdata.activity
 * 创建人：白彦东
 * 创建时间：2017/1/16 14:01
 * 修改备注：
 * ================================================
 */

public class OrdersDetailsActivity extends BaseActivity implements IPreviewCallBack {
    @Bind(R.id.orders_detail_tv_order_no)
    TextView ordersDetailTvOrderNo;
    @Bind(R.id.orders_detail_tv_order_status)
    TextView ordersDetailTvOrderStatus;
    @Bind(R.id.expand_list_view)
    ExpandableListView expandListView;

    // footer view
    private LinearLayout layoutFooterTop; // 顶部布局
    private TextView tvFooterLeft;
    private TextView tvFooterRight;
    private TextView tvContactSeller; // 联系卖家
    private TextView tvFooterGoodsAmount; // 商品金额
    private TextView tvFooterPreferentialAmount; // 优惠
    private TextView tvRealPay; // 实付款
    private TextView tvOrderTime; // 下单时间
    private TextView tvBtnLeft; // 左边按钮
    private TextView tvBtnRight; // 右边按钮

    private OrdersDetailsAdapter ordersDetailsAdapter;
    private List<CartVO> groupList = new ArrayList<>();
    private List<List<CartVO.ShoppingCartItemVOListBean>> childList = new ArrayList<>();
    private List<CartVO.ShoppingCartItemVOListBean> shoppingCartItemVOListBeen;

    private OrderListVO orderListVO;
    private List<OrderListVO.OrderItemsBean> orderItemVOList;

    private DataMallVO dataMallVO;
    private String resource; // 文件资源名
    private String resourceType; // 文件资源类型
    private String resourceTitle; // 文件资源标题
    private String resourceName; // 文件资源名称

    @Override
    public void setLayout() {
        setTitle("订单详情");
        setContentLayout(R.layout.activity_orders_details);
    }

    @Override
    public void initMember() {
        addFooterView();
        initExpandeListView();
        if (getIntent().hasExtra("OrderListVO"))
            orderListVO = (OrderListVO) getIntent().getSerializableExtra("OrderListVO");
        if (null != orderListVO)
            initData(orderListVO);
    }

    /**
     * 初始化Adapter数据
     */
    private void initData(OrderListVO data) {
        ordersDetailTvOrderNo.setText(String.format("订单号: %s", data.getOrderNo()));
        ordersDetailTvOrderStatus.setText(data.getEqualStatusDesc() != null ? data.getEqualStatusDesc() : "");

        setFooterLRText(data);

        setLeftAndRightButtonView(data);

        orderItemVOList = data.getOrderItems();
        for (int i = 0; i < orderItemVOList.size(); i++) {
            CartVO cartVO = new CartVO();
            List<CartVO.ShoppingCartItemVOListBean> itemVOListBeen = new ArrayList<>();
            CartVO.ShoppingCartItemVOListBean item = new CartVO.ShoppingCartItemVOListBean();
            item.setItemId(orderItemVOList.get(i).getProductId());
            item.setItemLogo(orderItemVOList.get(i).getProductImg());
            item.setItemName(orderItemVOList.get(i).getProductName());
            item.setItemSummary(orderItemVOList.get(i).getProductDesc());
            item.setItemPrice(orderItemVOList.get(i).getPrice());
            item.setItemQuantity("1"); // TODO 常量
            itemVOListBeen.add(item);
            cartVO.setShoppingCartItemVOList(itemVOListBeen);
            cartVO.setSupplierId(data.getSellerId());
            cartVO.setSupplierLogo(data.getSellerLogo());
            cartVO.setSupplierName(data.getSellerName());
            cartVO.setSupplierNumber(data.getSellerPhone());
//            cartVO.setSupplierAddress(data.getSellerAddress());
            groupList.add(cartVO);
            setListData(groupList, data.getEqualStatus());

            tvFooterGoodsAmount.setText(String.format("￥%s", getTotal()));
            tvRealPay.setText(String.format("实付款: ￥%s", orderListVO.getTotalPriceOrigin()));
            tvOrderTime.setText(String.format("下单时间: %s", DateUtil.StringToString(orderListVO.getCreateAt(), DateStyle.YYYY_MM_DD_EN_HH_MM_SS_EN)));
        }
    }

    /**
     * 设置左右安装及监听
     *
     * @param data
     */
    private void setLeftAndRightButtonView(OrderListVO data) {

        switch (data.getEqualStatus()) {
            case 29: // 待付款
                // 左边按钮
                tvBtnLeft.setText("取消订单");
                tvBtnLeft.setVisibility(View.VISIBLE);
                // 右边按钮
                tvBtnRight.setText("去  支  付");

                tvBtnLeft.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        showCancelReasonDialog();
                    }
                });
                tvBtnRight.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        //GotoUtil.gotoActivity(OrdersDetailsActivity.this, WXPayEntryActivity.class, "OrderListVO", orderListVO);
                    }
                });
                break;
            case 22: // 待评价
                // 左边按钮
                tvBtnLeft.setVisibility(View.GONE);
                // 右边按钮
                tvBtnRight.setText("去  评  价");
                tvBtnRight.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        GotoUtil.gotoActivity(OrdersDetailsActivity.this, EvaluateActivity.class, "OrderListVO", orderListVO);
                    }
                });
                break;
            case 23: // 已评价
                // 左边按钮
                tvBtnLeft.setVisibility(View.GONE);
                // 右边按钮
                tvBtnRight.setText("查看评价");
                tvBtnRight.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        GotoUtil.gotoActivity(OrdersDetailsActivity.this, EvaluateDetailsActivity.class, "OrderListVO", orderListVO);
                    }
                });
                break;
            case 24: // 已取消
                // 左边按钮
                tvBtnLeft.setVisibility(View.GONE);
                // 右边按钮
                tvBtnRight.setText("删除订单");
                tvBtnRight.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        showTipsDialog();
                    }
                });
                break;
        }
    }

    /**
     * 确定删除订单弹出框
     */
    private void showTipsDialog() {
    }

    /**
     * 根据订单状态 显示/隐藏 支付方式 取消原因
     * 22 - "待评价"
     * 23 - "已评价"
     * 24 - "已取消"
     * 29 - "待支付"
     * <p>
     * 0-支付宝
     * 1-微信
     *
     * @param orderListVO 订单
     */
    private void setFooterLRText(OrderListVO orderListVO) {
        switch (orderListVO.getEqualStatus()) {
            case 22:
                layoutFooterTop.setVisibility(View.VISIBLE);
                tvFooterLeft.setText("支付方式");
                tvFooterRight.setText("0".equals(orderListVO.getPaymentType()) ? "支付宝" : "微信");
                break;
            case 23:
                layoutFooterTop.setVisibility(View.VISIBLE);
                tvFooterLeft.setText("支付方式");
                tvFooterRight.setText("0".equals(orderListVO.getPaymentType()) ? "支付宝" : "微信");
                break;
            case 24:
                layoutFooterTop.setVisibility(View.VISIBLE);
                tvFooterLeft.setText("取消原因");
                tvFooterRight.setText(orderListVO.getBuyerCancelReason().toString()); // TODO 数据有问题
                break;
            case 29:
                layoutFooterTop.setVisibility(View.GONE);
                break;

        }
    }

    /**
     * 设置父子list
     *
     * @param groupList
     */
    private void setListData(List<CartVO> groupList, int orderStatus) {

        childList.clear();

        for (int i = 0; i < groupList.size(); i++) {
//            List<CartVO.ShoppingCartItemVOListBean> shoppingCartItemVOListBeen = groupList.get(i).getShoppingCartItemVOList();
            shoppingCartItemVOListBeen = groupList.get(i).getShoppingCartItemVOList();
            childList.add(shoppingCartItemVOListBeen);
        }

        ordersDetailsAdapter.setListData(groupList, childList, orderStatus);

        // 展开所有列表
        for (int i = 0; i < ordersDetailsAdapter.getGroupCount(); i++)
            expandListView.expandGroup(i);


    }

    /**
     * 为ExpandListView添加FooterView
     */
    private void addFooterView() {
        View footerView = LayoutInflater.from(this).inflate(R.layout.footer_view_for_order_details, null);
        layoutFooterTop = (LinearLayout) footerView.findViewById(R.id.footer_top_left_right_layout);
        tvFooterLeft = (TextView) footerView.findViewById(R.id.footer_orders_details_tv_left);
        tvFooterRight = (TextView) footerView.findViewById(R.id.footer_orders_details_tv_right);

        tvContactSeller = (TextView) footerView.findViewById(R.id.footer_orders_details_tv_contact_seller);
        tvFooterGoodsAmount = (TextView) footerView.findViewById(R.id.footer_orders_details_tv_goods_amount);
        tvFooterPreferentialAmount = (TextView) footerView.findViewById(R.id.footer_orders_details_tv_preferential);
        tvRealPay = (TextView) footerView.findViewById(R.id.footer_orders_details_tv_real_pay);
        tvOrderTime = (TextView) footerView.findViewById(R.id.footer_orders_details_tv_order_time);

        tvBtnLeft = (TextView) footerView.findViewById(R.id.tv_btn_left);
        tvBtnRight = (TextView) footerView.findViewById(R.id.tv_btn_right);

        expandListView.addFooterView(footerView);
    }

    /**
     * 初始化 ExpandListView
     */
    private void initExpandeListView() {
        ordersDetailsAdapter = new OrdersDetailsAdapter(this, groupList, childList, this);
        expandListView.setAdapter(ordersDetailsAdapter);
        expandListView.setGroupIndicator(null);
        expandListView.setDividerHeight(2);
    }

    /**
     * 获取商品的总价
     *
     * @return 总价
     */
    private String getTotal() {
        String total = "0.00";
        for (int i = 0; i < groupList.size(); i++) {
            for (int j = 0; j < childList.get(i).size(); j++) {
                total = MathExtend.add(total, MathExtend.multiply(childList.get(i).get(j).getItemPrice(), childList.get(i).get(j).getItemQuantity()));
            }

        }
        return String.valueOf(total);
    }

    /**
     * 显示取消订单原因
     */
    private void showCancelReasonDialog() {
        CustomDialog.orderCancelReasonDialog(OrdersDetailsActivity.this, mHandler);
    }

    @Override
    public void addListener() {

    }

    @Override
    public void setHandler() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case MSG.MSG_SELECT_ORDER_CANCEL_REASON_TAG: // 选择取消原因提交
                        BusinessOrders.cancelOrder(OrdersDetailsActivity.this, orderListVO.getOrderNo(), ((CancelReasonVO) msg.obj).getCancelReason(), mHandler);
                        break;
                    case MSG.MSG_CANCEL_ORDER_SUCCESS: // 订单取消成功
                        orderListVO.setEqualStatus(24);
                        setLeftAndRightButtonView(orderListVO);
                        ordersDetailTvOrderStatus.setText("已取消"); // 订单状态
                        break;
                    case MSG.MSG_CANCEL_ORDER_FIELD:
                        showToast(msg.obj.toString());
                        break;
                    case MSG.MSG_DELETE_ORDER_SUCCESS:
                        showToast("订单已删除");
                        finish();
                        break;
                    case MSG.MSG_DELETE_ORDER_FIELD:
                        showToast(msg.obj.toString());
                        break;
                    case MSG.MSG_PRODUCT_DETAILS_SUCCESS: // 商品详情
                        callBack(msg.obj);
                        break;
                    case MSG.MSG_PRODUCT_DETAILS_FIELD:
                        dismissDialog();
                        showToast(msg.obj.toString());
                        break;
                }
            }
        };
    }

    @Override
    public void callBack(Object object) {
        dataMallVO = FastJsonUtil.getBean(object.toString(), "body", "commodityInfo", DataMallVO.class);
        resource = dataMallVO != null ? dataMallVO.getResource() : "";
        resourceType = dataMallVO != null ? dataMallVO.getResourceType() : "";
        resourceTitle = dataMallVO != null ? dataMallVO.getTitle() : null;
        resourceName = StringUtil.jointString(resource, ".", resourceType);

        String resPath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "Downloads" + File.separator;
        String fileName = resourceName;

        if (null == dataMallVO)
            return;

        FileDownloader.getImpl().create(URL.URL_FILE_DOWNLOAD + resource)
                .setPath(resPath + fileName)
                .setListener(new FileDownloadLargeFileListener() {
                    @Override
                    protected void pending(BaseDownloadTask task, long soFarBytes, long totalBytes) {
                        LogUtils.e("pending");
                    }

                    @Override
                    protected void progress(BaseDownloadTask task, long soFarBytes, long totalBytes) {
                        LogUtils.e("progress" + soFarBytes + " : " + totalBytes);
                    }

                    @Override
                    protected void paused(BaseDownloadTask task, long soFarBytes, long totalBytes) {
                        LogUtils.e("paused");
                    }

                    @Override
                    protected void completed(BaseDownloadTask task) {
                        dismissDialog();
//                        openFile(OrdersDetailsActivity.this, task.getTargetFilePath());
                        MIMETypeUtil.openFile(OrdersDetailsActivity.this, new File(task.getTargetFilePath()));
                    }

                    @Override
                    protected void error(BaseDownloadTask task, Throwable e) {
                        dismissDialog();
                        LogUtils.e("error");
                    }

                    @Override
                    protected void warn(BaseDownloadTask task) {
                        LogUtils.e("warn");
                    }
                }).start();
    }

    @Override
    public void rightOnClick() {

    }

    @Override
    public void onlinePreviewClick(int pos) {

        showDialog("");
        BusinessDataMall.productdetails(this, orderItemVOList.get(pos).getProductId(), mHandler);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
